package model;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFileClass {
	private boolean isMultipart;
	private String filePath;
	private int maxFileSize = 50000 * 1024;
	private int maxMemSize = 50000 * 1024;
	private File file;

	public UploadFileClass() {

	}

	public void init(String fileuploadpath) {
		// Get the file location where it would be stored.
		filePath = fileuploadpath;
	}

	public boolean Upload(HttpServletRequest request) {
		boolean succes;
		// Check that we have a file upload request
		isMultipart = ServletFileUpload.isMultipartContent(request);
		String alterResult = "";

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(maxMemSize);
		// Location to save data that is larger than maxMemSize.
		factory.setRepository(new File("c://temp"));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum file size to be uploaded.
		upload.setSizeMax(maxFileSize);

		try {
			// Parse the request to get file items.
			List fileItems = upload.parseRequest(request);

			// Process the uploaded file items
			Iterator i = fileItems.iterator();

			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (!fi.isFormField()) {
					// Get the uploaded file parameters
					String fieldName = fi.getFieldName();
					String fileName = fi.getName();
					String contentType = fi.getContentType();
					boolean isInMemory = fi.isInMemory();
					long sizeInBytes = fi.getSize();
					// Write the file
					if (fileName.lastIndexOf("\\") >= 0) {
						file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
					} else {
						file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
					}
					fi.write(file);					
				}
			}
			succes = true;
		} catch (Exception ex) {
			ex.printStackTrace();
			succes = false;
		}
		return succes;
	}

	public int getMaxFileSize() {
		return maxFileSize;
	}

	public void setMaxFileSize(int maxFileSize) {
		this.maxFileSize = maxFileSize;
	}

	public int getMaxMemSize() {
		return maxMemSize;
	}

	public void setMaxMemSize(int maxMemSize) {
		this.maxMemSize = maxMemSize;
	}

	public String getFilePath() {
		return filePath;
	}

	public File getFile() {
		return file;
	}
}
